import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import datetime


class NeimengguWlcbshdxrmzfBc4EPolicy(BaseTaxPolicySpider):
    name = "neimenggu_wlcbshdxrmzf_bc4e_policy"

    province: str = "内蒙古自治区"  # 取表格
    city: str = "乌兰察布市"  # 取表格
    county: str = "化德县"  # 取表格
    park: str = "None"  # 取表格
    source: str = "乌兰察布市化德县人民政府"  # 取表格 同一个来源合并
    url: str = "https://www.huade.gov.cn/xxyxgfxwjk/index.html"  # 注明入口网址，以便后续排错
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        # 'Cookie': 'jeeplus.session.rmtapi.id=aff37a772c4347bdb0638ccb38efa62f; pageNo=1; pageSize=10',
        'Origin': url,
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0',
        'X-Requested-With': 'XMLHttpRequest',
        'sec-ch-ua': '"Microsoft Edge";v="125", "Chromium";v="125", "Not.A/Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
    }
    host_url = url.split('.gov.cn')[0] + '.gov.cn'

    def start_requests(self):
        yield scrapy.Request(self.url, callback=self.return_content)

    def return_content(self, response, **kwargs):
        url = f"{self.host_url}/rmt/a/api/zwgk/files/findFilesList"
        id = response.xpath("//script").re_first(r"""var id\s*=\s*\"(.*)\"""")
        print(id)
        data = {
            'siteId': id,
            'type': '0',
            'keyword': '',
            'topicClassId': '',
            'publishAgency': 'all',
            'docNumber': '',
            'inputTime': '',
            'inputTimeEnd': '',
            'publishTime': '',
            'publishTimeEnd': '',
            'pageSize': '10',
            'pageNo': '1',
        }
        # data = json.dumps(data, separators=(',', ':'))
        yield scrapy.FormRequest(url, formdata=data, callback=self.parse_list, meta={"data": data},
                                 headers=self.headers)

    def parse_list(self, response, **kwargs):
        # print(response.text)
        prev_item = response.meta.get('item')
        for elem in response.json()['data']:
            item = Item()
            item['source_url'] = elem['docurl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = datetime.datetime.fromtimestamp(elem['inputTime'] / 1000)
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            data = response.meta.get('data')
            total_page = response.json()['allPage']
            for page_num in range(2, int(total_page) + 1):
                data['pageNo'] = str(page_num)
                yield scrapy.FormRequest(response.url, formdata=data, callback=self.parse_list, headers=self.headers,
                                         meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl neimenggu_wlcbshdxrmzf_bc4e_policy".split())
